# -*- coding: utf-8 -*-
from pymongo import MongoClient
from func import Func


class MyMongoClient:
    def __init__(self, host, port, server_port=None, ip=None, *args,
                 **kwargs):
        #  标志 D J A 区分
        self.client = MongoClient(host=host, port=int(port))

        self.id_pools = self.client.guidang4.id_pools
        self.capture = self.client.guidang4.capture
        self.card = self.client.guidang4.card
        self.cardacvs = self.client.guidang4.cardacvs
        self.cardface = self.client.guidang4.cardface
        self.record = self.client.guidang4.record
        self.insert_fail = self.client.guidang4.insert_fail
        self.config = self.client.guidang4config.config
        self.logcount_ = self.client.guidang4.logcount
        self.acvs = self.client.guidang4.acvs

        if ip is not None:
            self.ip = ip
            self.server_port = server_port

            self.config_D = self.config.find_one({'_id': '%s_%s_D' % (self.ip, self.server_port)})
            self.config_J = self.config.find_one({'_id': '%s_%s_J' % (self.ip, self.server_port)})
            self.config_A = self.config.find_one({'_id': '%s_%s_A' % (self.ip, self.server_port)})

            self.box_ip_D = self.config_D.get('h_ip')
            self.box_ip_J = self.config_J.get('h_ip')
            self.box_ip_A = self.config_A.get('h_ip')

            self.box_port_D = self.config_D.get('h_port')
            self.box_port_J = self.config_J.get('h_port')
            self.box_port_A = self.config_A.get('h_port')

            self.box_uname_D = self.config_D.get('h_uname')
            self.box_uname_J = self.config_J.get('h_uname')
            self.box_uname_A = self.config_A.get('h_uname')

            self.box_upassword_D = self.config_D.get('h_pwd')
            self.box_upassword_J = self.config_J.get('h_pwd')
            self.box_upassword_A = self.config_A.get('h_pwd')

            self.func_client_D = Func(self.box_ip_D, self.box_port_D, self.box_uname_D, self.box_upassword_D)
            self.func_client_J = Func(self.box_ip_J, self.box_port_J, self.box_uname_J, self.box_upassword_J)
            self.func_client_A = Func(self.box_ip_A, self.box_port_A, self.box_uname_A, self.box_upassword_A)

        # 贺昌浩
        self.run_mongo_time = self.client.guidang4.runmongo_time

    def del_card_mongo(self, card_id, acvs_list):
        self.capture.delete_one({"_id": card_id})
        self.card.delete_one({"_id": card_id})
        cardacvs_res = self.cardacvs.delete_many({"card_id": card_id})
        print("cardacvs_count:", cardacvs_res.deleted_count)
        cardface_res = self.cardface.delete_many({"card_id": card_id})
        print("cardface_count:", cardface_res.deleted_count)
        for acvs_id in acvs_list:
            self.acvs.update_one({"_id": acvs_id}, {"$inc": {"lencard": -1}})

    def insert_fail_img(self, data_dic):
        self.insert_fail.insert_one(data_dic)

    def drop_all(self):
        self.client.drop_database(self.client.guidang4)

    def init_mongo(self):

        if self.logcount_.find_one({'_id': 'logCount'}) is None:
            self.logcount_.insert_one(
                {
                    "_id": "logCount",
                    "count": 1
                }
            )

        if 'id_pools' not in self.client.guidang4.list_collection_names():
            self.id_pools.insert_one({
                '_id': 'idpools',
                'face_id': 1
            })

        self.config.update({'_id': '%s_%s_D' % (self.ip, self.server_port)},
                           {'$set': {'c1': 0, 'c2': 0, 'c3': 0, 'now_id': 'ID1'}})
        self.config.update({'_id': '%s_%s_J' % (self.ip, self.server_port)},
                           {'$set': {'c1': 0, 'c2': 0, 'c3': 0, 'now_id': 'ID1'}})
        self.config.update({'_id': '%s_%s_A' % (self.ip, self.server_port)},
                           {'$set': {'c1': 0, 'c2': 0, 'c3': 0, 'now_id': 'ID1'}})

    def get_current_use_repo(self, repo_type):
        if repo_type == 'D':
            func_client = self.func_client_D
        if repo_type == 'J':
            func_client = self.func_client_J
        if repo_type == 'A':
            func_client = self.func_client_A

        name_id = '%s_%s_%s' % (self.ip, self.server_port, repo_type)
        # 很重要 区分 D J A
        config_info = self.config.find_one({'_id': name_id})
        repo_key = config_info.get('now_id')
        repo = config_info.get(repo_key)

        repo_count = config_info.get('c%s' % repo_key[-1])
        repo_max = config_info.get('m%s' % repo_key[-1])

        id1 = config_info.get('ID1')
        id2 = config_info.get('ID2')
        id3 = config_info.get('ID3')

        if repo_count >= repo_max:
            if repo == id3:
                new_repo = id1
                # 删库1 升级mongo
                if self.change_repo(name_id, '1'):
                    func_client.delete_repo(new_repo)
                    func_client.create_repo(new_repo, '%s_%s' % (repo_type, '1'))
                    return new_repo, "ID1"

            if repo == id2:
                new_repo = id3
                # 删库3 升级mongo
                if self.change_repo(name_id, '3'):
                    func_client.delete_repo(new_repo)
                    func_client.create_repo(new_repo, '%s_%s' % (repo_type, '3'))
                    return new_repo, "ID3"

            if repo == id1:
                new_repo = id2
                # 删库2 升级mongo
                if self.change_repo(name_id, '2'):
                    func_client.delete_repo(new_repo)
                    func_client.create_repo(new_repo, '%s_%s' % (repo_type, '2'))
                    return new_repo, "ID2"

        return repo, repo_key

    def get_hezi_face_id(self):
        return self.id_pools.find_one_and_update({'_id': 'idpools'}, {'$inc': {'face_id': 1}}, upsert=True)['face_id']

    def change_repo(self, name_id, new_repo):
        result1 = self.config.update_one({'_id': name_id}, {'$set': {'now_id': 'ID%s' % new_repo, 'c%s' % new_repo: 0}})
        return result1.acknowledged

    def inc_count(self, repo_id_key, repo_type):
        name = '%s_%s_%s' % (self.ip, self.server_port, repo_type)

        self.config.update_one({'_id': name}, {'$inc': {'c%s' % repo_id_key[-1]: 1}})

    def ins_capture(self, data):
        self.capture.insert_one(data)

    def updata_capture(self, id, feature, name, person_id, uri):
        self.capture.update_one({'_id': id}, {
            '$set': {'ovn_f': feature, 'name': name, 'person_id': person_id, 'face_image_uri': uri}}, upsert=True)

        self.card.update_one({'_id': id}, {'$set': {'name': name, 'person_id': person_id, 'face_image_uri': uri}})
        self.cardacvs.update_many({'card_id': id}, {
            '$set': {'ovn_f': feature, 'name': name, 'person_id': person_id, 'face_image_uri': uri}})
        self.cardface.update_many({'card_id': id}, {
            '$set': {'card_name': name, 'card_person_id': person_id, 'card_face_image_uri': uri}})

    def get_record(self):
        return list(self.record.find())

    # 贺昌浩
    def update_time(self, max_time):
        self.run_mongo_time.update_one({'_id': 'run1_mongo_time'}, {'$set': {'update_time': max_time}}, upsert=True)

    def get_time(self):
        return self.run_mongo_time.find_one({'update_time': {'$exists': True}})

    def insert_cap(self, dic):
        id = dic.pop('_id')
        return self.capture.update_one({'_id': id}, {'$set': dic}, upsert=True)

    def get_face_base64(self, face_image_id):
        return self.capture.find_one({'_id': face_image_id})

    def update_ovo(self, face_image_id, ovo_f):
        return self.capture.update_one({'_id': face_image_id}, {'$set': {'ovo_f': ovo_f}}, upsert=True)

    def update_card_info(self, card_id, face_image_uri, name, person_id):
        self.card.update_one({'_id': card_id},
                             {'$set': {'face_image_uri': face_image_uri, 'name': name, 'person_id': person_id}})

        self.cardacvs.update_many({'face_image_id': card_id},
                                  {'$set': {'name': name, 'person_id': person_id, 'face_image_uri': face_image_uri}})

        self.cardface.update_many({'card_id': card_id},
                                  {'$set': {"card_person_id": person_id, "card_face_image_uri": face_image_uri,
                                            "card_picture_uri": face_image_uri, "card_name": name}})
